package tree;

import sun.reflect.generics.tree.Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName minDepth
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-09 20:21
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class minDepth {

    /**
     * 给定一个二叉树，找出其最小深度。
     * <p>
     * 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
     * <p>
     * 说明：叶子节点是指没有子节点的节点。
     *
     * @param treeNode
     * @return
     */
    public int minDepth(TreeNode treeNode) {
        if (treeNode == null) {
            return 0;
        }

        int res = 1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(treeNode);

        while (!queue.isEmpty()) {

            int size = queue.size();

            while (size > 0) {
                TreeNode poll = queue.poll();
                if (poll.right == null && poll.left == null) return res;

                if (poll.left != null) queue.add(poll.left);
                if (poll.right != null) queue.add(poll.right);
                size--;
            }
            res++;
        }
        return res;
    }

    public int minDepth1(TreeNode root) {
        if (root == null) return 0;

        if (root.left == null)
            return minDepth1(root.right) + 1;
        if (root.right == null)
            return minDepth1(root.left) + 1;
        // 左右子树都不为空时
        return Math.min(minDepth1(root.left), minDepth1(root.right)) + 1;
    }


    public static void main(String[] args) {
        minDepth minDepth = new minDepth();

        TreeNode treeNode = new TreeNode(2);

        TreeNode treeNodeLeft = new TreeNode(1);
        treeNode.left = treeNodeLeft;

        TreeNode treeNodeLeft1 = new TreeNode(1);
        treeNodeLeft.left = treeNodeLeft1;

        TreeNode treeNodeRight = new TreeNode(3);
        treeNode.right = treeNodeRight;

        System.out.println(minDepth.minDepth(treeNode));
    }
}